<script lang="ts">
export default {
  name: 'CourtTable',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin, PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { deleteCourt, getCourtList, updateCourt } from '@/api/court';
import { CourtModel } from '@/api/model/CourtModel';
import { prefix } from '@/config/global';
import { useSettingStore } from '@/store';

const store = useSettingStore();
const COLUMNS: PrimaryTableCol<TableRowData>[] = [
  { title: '场地名称', colKey: 'courtName', fixed: 'left' },
  { title: '场地类型', colKey: 'courtType' },
  { title: '场地容量', colKey: 'capacity' },
  { title: '管理员', colKey: 'manager' },
  { title: '是否启用', colKey: 'status' },
  { title: '创建时间', colKey: 'createdAt' },
  { title: '更新时间', colKey: 'updatedAt' },
  {
    title: '操作',
    align: 'left',
    fixed: 'right',
    colKey: 'op',
  },
];

const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});

const searchValue = ref('');

const dataLoading = ref(false);

const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list, pageSize, pageIndex } = await getCourtList({
      pageSize: pagination.value.defaultPageSize,
      pageIndex: pagination.value.defaultCurrent,
    });
    console.log(list, pageSize, pageIndex);
    data.value = list;
    pagination.value = {
      defaultPageSize: pageSize,
      defaultCurrent: pageIndex,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { courtName } = data.value[deleteIdx.value];
    return `删除后，场地${courtName}的所有信息将被清空，且无法恢复`;
  }
  return '';
});

onMounted(() => {
  fetchData();
});

const confirmVisible = ref(false);

const selectedRowKeys = ref([]);

const router = useRouter();

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = async () => {
  // 真实业务请发起请求
  const targetData = data.value.splice(deleteIdx.value, 1);
  pagination.value.total = data.value.length;
  confirmVisible.value = false;
  try {
    await deleteCourt(targetData[0].courtId);
    await MessagePlugin.success('删除成功');
    fetchData();
  } catch (e) {
    await MessagePlugin.error(e?.message || '删除失败');
  }
  resetIdx();
};

const onCancel = () => {
  resetIdx();
};

const rowKey = 'courtId';

/** 点击获取详情 */
const handleClickDetail = (data: { row: { courtId: string } }) => {
  const { courtId } = data.row;
  router.push({
    path: '/court/update',
    query: { courtId },
  });
};

const handleSetupContract = () => {
  router.push('/court/create');
};

const handleClickDelete = (row: { rowIndex: any }) => {
  deleteIdx.value = row.rowIndex;
  console.log(deleteIdx.value);
  confirmVisible.value = true;
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any,
);

const handleChangeCourtStatus = async (row: CourtModel) => {
  console.log(row.courtId, row.status);
  const res = await updateCourt({ courtId: row.courtId, status: row.status });
  if (res) {
    await MessagePlugin.success('操作成功');
  } else {
    await MessagePlugin.error('操作失败');
  }
};
</script>

<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="handleSetupContract"> 创建场地</t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选择 {{ selectedRowKeys.length }} 项</p>
        </div>
        <div class="search-input">
          <t-input v-model="searchValue" :placeholder="$t('pages.listBase.placeholder')" clearable>
            <template #suffix-icon>
              <search-icon size="16px" />
            </template>
          </t-input>
        </div>
      </t-row>
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        table-layout="auto"
        vertical-align="middle"
        :pagination="pagination"
        :loading="dataLoading"
        :hover="true"
        :stripe="true"
        :selected-row-keys="selectedRowKeys"
        :header-affixed-top="headerAffixedTop"
      >
        <template #status="{ row }">
          <t-switch v-model="row.status" variant="light-outline" @change="handleChangeCourtStatus(row)"> </t-switch>
        </template>
        <template #createdAt="{ row }">
          <span>{{ dayjs(row.createdAt).format('YYYY-MM-DD HH:mm') }}</span>
        </template>
        <template #updatedAt="{ row }">
          <span>{{ dayjs(row.createdAt).format('YYYY-MM-DD HH:mm') }}</span>
        </template>
        <template #op="slotProps">
          <t-space>
            <t-dropdown placement="right">
              <t-button theme="default" variant="text" shape="square">
                <t-icon name="ellipsis" size="16" />
              </t-button>
              <t-dropdown-menu>
                <t-dropdown-item :divider="true" @click="handleClickDetail(slotProps)">详情</t-dropdown-item>
                <t-dropdown-item theme="error" @click="handleClickDelete(slotProps)">删除</t-dropdown-item>
              </t-dropdown-menu>
            </t-dropdown>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选合同？"
      :body="confirmBody"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);

  .selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-l);
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  width: 360px;
}
</style>
